import * as toast from '@/util/toast/toast'
var util = {}


util.formatDate = (time) => {
    return moment(time).format('yyyy-MM-dd HH:mm')
}

util.dealUrl = (url)=>{
    if (url) {
      if (url.indexOf('http') !== -1) {
        return url
      } else if (url.indexOf('https') !== -1) {
        return url
      } else {
        return process.env.VUE_APP_API_URL + url
      }
    }
  }

  util.weixinUploadFile = (param,callback) => {
    console.log('微信小程序开始上传图片了');
     // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
     wx.uploadFile({
      url: 'http://app.liyusongli.com/api/common/upload/filetoAliyunOSS', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      header:{
        'Content-Type': 'multipart/form-data',
      },
      formData: { method: 'POST' },
      success(res) {
        let result = JSON.parse(uploadFileRes.data)

        console.log('错误码:' + result.code)
        if(result.code === 0){
          console.log('图片的上传地址:' + result.data.url)

          callback(result.data.url)


        }else{
            toast.infoToast(result.msg)
        }
      },
      fail(error){
        toast.infoToast(error.msg)
      }
    });
  }

  // 选择+拍照上传

  util.choooseAndUploadPhoto = (callback)=> {

    let that = this;
    uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        success: function (res) {
            console.log(JSON.stringify(res.tempFilePaths));
            toast.showLoading('上传中')
   
                    uni.uploadFile({
                      url: 'https://ydpt.wincrosoft.net/appapi/Upload/uploadfile', // 仅为示例，非真实的接口地址
                      // filePath:res.tempFilePath,
                        filePath:res.tempFilePaths[0],
                        name:'file',
                        success:function(uploadFileRes){
                          toast.hideLoading()

                          let result = JSON.parse(uploadFileRes.data)
                          console.log('图片的上传地址:' + JSON.stringify(result))

                          toast.hideLoading()
                          if(result.success){
                            console.log('图片的上传地址:' + result.data)

                            callback(result.data)
                          }else{
                              toast.infoToast(result.msg)
                          }
                        },
                        fail:(error) =>{
                          toast.hideLoading()
                          console.log('上传错误:' + error)
                          callback(null)
                        }
                    });


          },
          fail:(error) =>{
            console.log('拍照错误:' + error)
            callback(null)
          }
        })

    
  }


  ///将地址转换成邮编
util.queryAddressCodeFromName = (name)=>{
  let addressList = name.split(' ')
  if(addressList.length === 3){

     let county_name = addressList[2]
    let  county_list = areaList.county_list

    let county_code = ''

    Object.keys(county_list) && Object.keys(county_list).forEach(key => {
      let val = county_list[key]
      if (val === county_name) {
        county_code = key
      }
    })
  
    return county_code
  }
  return name

}


///将邮编转换成地址信息
util.queryAddressNameFromCode = (code)=>{


  // province_list: {
  //   110000: '北京市',
  //   120000: '天津市',
  // },
  // city_list: {
  //   110100: '北京市',
  //   120100: '天津市',
  // },
  // county_list: {
  //   110101: '东城区',
  //   110102: '西城区',
  //   // ....
  // }

  let  province_list = areaList.province_list
  let  city_list = areaList.city_list
  let  county_list = areaList.county_list
  if(code.length === 6){
  
      let province_code = code.substring(0,3) + '000'
      let city_code = code.substring(0,4) + '00'

      
      let provice_name = province_list[province_code]
      let city_name = city_list[city_code]
      let county_name = county_list[code]

      // console.log('省code:' + province_code)
      // console.log('市code:' + city_code)
      // console.log('区code:' + code)

      // console.log('省:' + provice_name)
      // console.log('市:' + city_name)
      // console.log('区:' + county_name)

      let address = provice_name + ' ' + city_name + ' ' + county_name
      return address
  }

  return code

}

util.isIos = () => {
  const u = navigator.userAgent
  const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1 // g
  const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
  if (isAndroid) {
    // 这个是安卓操作系统
    return false
  }
  if (isIOS) {
    // 这个是ios操作系统
    return true
  }
}

///查询缓存大小
// util.getStorageCacheInfo=()=>{
  export function getStorageCacheInfo(){

  let size = 0

  uni.getStorageInfo({
    success:function(res){
      let cache = res.currentSize / ( 1024 * 1024 )
      let val = res.currentSize
      var k = 1024;
      var sizes = ['B','KB','MB','GB','PB','TB','EB','ZB','YB'],
      i = Math.floor(Math.log(val) / Math.log(k));
      cache = (val / Math.pow(k,i)).toPrecision(1) + "" + sizes[i]

      console.log('缓存大小:' + cache)
      size = cache
    }
  })
  return size
}

///清除缓存
export function clearStorageCacheInfo(){
// util.clearStorageCacheInfo = ( callback) => {
  try {
    uni.clearStorageSync()
  }catch(e){

  }
}

///解析出url中的参数
util.parseParamDictFormUrl = ( url) => {
  if(url.includes('?') === false){
    return null
  }
  let  list = url.split('?')
  if(list.length < 2){
    return null
  }
  let paramStr = list[1]
  let paramList = paramStr.split('&')
  let res = {}

  paramList.forEach(element => {
    let temp = element.split('=')
    if(temp.length == 2){
       let key = temp[0]
       let val = temp[1]
       res[key] = val
    }
  });
  return res

}

///解析出url中的参数
util.filterNullStr =  (str,place)=>{
  if(str === null || str === undefined || str === ''){
    return place
  }else{
    return str
  }

}

// export function filterNullStr(str,place){
//   if(str === null || str === undefined || str === ''){
//     return place
//   }else{
//     return str
//   }
// }


export default util
